// 获取用户已答对的题目API
import { NextRequest } from 'next/server';
import { AnswerDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

/**
 * GET /api/practice/correct-answers
 * 获取用户已答对的题目列表
 * 
 * 查询参数:
 * - topicId?: string - 可选，指定知识点ID
 */
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const topicId = searchParams.get('topicId');

    // 获取已答对的题目
    const correctAnswers = await AnswerDB.getCorrectAnswersByUser(
      currentUser.userId,
      topicId || undefined
    );

    // 按知识点分组
    const groupedByTopic: Record<string, number[]> = {};
    correctAnswers.forEach((record) => {
      if (!groupedByTopic[record.topic_id]) {
        groupedByTopic[record.topic_id] = [];
      }
      groupedByTopic[record.topic_id].push(record.question_index);
    });

    return ApiResponse.success({
      correctAnswers,
      groupedByTopic,
      total: correctAnswers.length,
    });
  } catch (error) {
    console.error('获取已答对题目错误:', error);
    return ApiResponse.serverError('获取已答对题目失败');
  }
}

